<template>
  <div>
    <!-- 搜索栏 -->
    <el-form
      :model="searchForm.data"
      label-width="auto"
      :ref="searchForm.ref"
      @submit.prevent="searchForm.onSubmit"
    >
      <el-form-item>
        <el-col :span="6">
          <el-form-item
            label="角色名称:"
            prop="name"
          >
            <el-input
              v-model="searchForm.data.name"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          style="margin-left: 16px;"
        >
          <el-button
            type="primary"
            @click="searchForm.onSubmit"
          >
            <template #icon>
              <Search />
            </template>搜索</el-button>
          <el-button @click="searchForm.onClear">
            <template #icon>
              <Refresh />
            </template>重置</el-button>

        </el-col>
      </el-form-item>
      <el-form-item v-permission="['sys:usermgr:role:add']">
        <el-button
          @click="onAdd"
          type="success"
        >
          <template #icon>
            <Plus />
          </template>新增</el-button>
      </el-form-item>
    </el-form>
    <FormDialog
      ref="dialogAddEditRef"
      :formFields="fields"
      :formHandlers="formHandlers"
      @success="onDialogSuccess"
    />
    <PTable
      :dataColumns="fields"
      :table="table"
    />
    <RolePermissionDialog
      ref="dialogPermissionRef"
      title="分配权限"
      @success="onDialogSuccess"
    >
    </RolePermissionDialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import FormDialog from '@/components/FormDialog.vue'
import PTable from '@/components/PTable.vue'
import { FormMode } from '@/common/type/baseEnum'
import type { RoleData } from '@/common/type/data'
import type { SearchForm } from '@/common/type/form'
import { DefaultPagTable, type PagTable } from '@/common/type/table'
import { addRoleInfo, editRoleInfo, getRoleInfo } from '@/api/usermgr'
import { ElMessage } from 'element-plus'
import { isResultSuccess } from '@/util/http'
import { deleteRoleInfo } from '@/api/usermgr'
import Logger from '@/util/log'
import type { CommonField } from '@/common/type/field'
import RolePermissionDialog from '@/views/usermgr/RolePermissionDialog.vue'

// 搜索框
const searchForm: SearchForm = {
  data: reactive({
    name: '',
  }),

  ref: ref(),
  onSubmit: () => {
    console.log('search submit!', searchForm.data.name)
    table.initTableData()
  },
  onClear: () => {
    searchForm.ref.value.resetFields()
    table.initTableData()
  },
}

// 新增编辑按钮
const dialogAddEditRef = ref()
const onAdd = () => {
  dialogAddEditRef.value.open(FormMode.Add)
}

const dialogPermissionRef = ref()

const fields: CommonField[] = [
  {
    prop: 'idx',
    label: '序号',
    formMeta: {
      hideInForm: true,
    },
    tableMeta: {
      width: '66',
      type: 'index'
    },
  },
  {
    label: '角色名称',
    prop: 'name',
    formMeta: {
      disabledOn: [FormMode.Edit],
      rules: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
    },
  },
  {
    label: '角色描述',
    prop: 'description',
    formMeta: {
      rules: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
    },
    tableMeta: {
      showOverflowTooltip: true,
    }
  },
  {
    label: '创建时间',
    prop: 'created_at',
    formMeta: {
      hideInForm: true,
    },
    tableMeta: {
      formatter(row, column, cellValue, index) {
        return cellValue.replace('T', ' ').slice(0, 19)
      }
    }
  }
]

const formHandlers = new Map([
  [FormMode.Add, addRoleInfo],
  [FormMode.Edit, editRoleInfo],
])

const table: PagTable<RoleData> = new DefaultPagTable({
  refreshTableData: async () => {
    try {
      const res = await getRoleInfo({
        pageNo: table.pagination.currentPage as number,
        pageSize: table.pagination.pageSize,
        roleName: searchForm.data.name ? searchForm.data.name : undefined
      })
      Logger.prettyInfo('getRoleInfo', res)
      if (res && isResultSuccess(res)) {
        table.data.splice(0, table.data.length, ...res.data.list)
        table.pagination.total = res.data.total || res.data.list.length
      }
    } catch (error) {
      Logger.prettyError('getRoleInfo catch error', error)
    }
  },
  onTableDataEdit: (index: number, row: RoleData) => {
    dialogAddEditRef.value.open(FormMode.Edit, row)
  },
  editPermissionCode: 'sys:usermgr:role:edit',
  deletePermissionCode: 'sys:usermgr:role:delete',
  onTableDataDelete: async (index: number, row: RoleData) => {
    Logger.prettyInfo('deleteRoleInfo', row)
    let success = false, errMsg: any
    try {
      const res = await deleteRoleInfo({ "role_name": row.name })
      success = isResultSuccess(res)
      errMsg = res.msg
    } catch (error) {
      errMsg = error
      Logger.prettyError('deleteRoleInfo catch error', error.response.data)
    }
    if (!success) {
      ElMessage({
        message: '删除角色失败！' + errMsg,
        type: 'error',
        duration: 1500
      })
    } else {
      ElMessage({
        message: '删除角色成功！',
        type: 'success',
        duration: 1500
      })
      table.initTableData()
    }
  },
  extraOperations: [
    {
      onDataOperation: (index: number, row: RoleData) => {
        dialogPermissionRef.value.open(FormMode.Edit, row)
      },
      permissionCode: 'sys:usermgr:role:permission',
      icon: 'position',
    }
  ]
})

const onDialogSuccess = () => {
  table.initTableData()
}
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end
}
</style>
